<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <el-card >

    <div class="filter-container">
<!--      <el-select v-if="!shop" v-model="listQuery.shopId" clearable class="filter-item" :placeholder="$t('请选择门店')">
        <el-option v-for="item in shops" :value="item.id" :label="item.name"></el-option>
      </el-select>

      <el-cascader :placeholder="$t('请选择区域地址')" class="filter-item" v-model="regionIds" :options="countrys"
        @active-item-change="handleItemChange" :props="props" clearable filterable></el-cascader>

      <el-button class="filter-item" type="primary" plain1 icon="el-icon-search"
        @click="handleFilter">{{$t('Search')}}</el-button>-->
      <el-button v-if="shop" v-permission="['GET /admin/p/store_accountbook_add']" class="filter-item" type="info"
        plain1 icon="el-icon-plus" @click="handleAdd">{{$t('Add')}}</el-button>
    </div>
    <div class="table-layout">
      <el-row>
          <el-col :span="6" class="table-cell-title">{{$t('订单金额')}}/{{$t('总税费')}}</el-col>
          <el-col :span="3" class="table-cell-title">{{$t('总店充值')}}</el-col>
          <el-col :span="3" class="table-cell-title">{{$t('门店现金总充值')}}</el-col>
          <el-col :span="3" class="table-cell-title">{{$t('额外总收入')}}</el-col>
          <el-col :span="3" class="table-cell-title">{{$t('额外总支出')}}</el-col>
          <el-col :span="3" class="table-cell-title">{{$t('采购总支出')}}</el-col>
          <el-col :span="3" class="table-cell-title">{{$t('导入原料总支出')}}</el-col>
      </el-row>
      <el-row>
          <el-col :span="6" class="table-cell">
              ${{shopSummary.totalOrderActualPrice}} /
              <el-link type="primary">GST ${{shopSummary.totalTaxGST}}</el-link><el-divider direction="vertical"></el-divider>
              <el-link type="success">HST ${{shopSummary.totalTaxHST}}</el-link><el-divider direction="vertical"></el-divider>
              <el-link type="warning">PST ${{shopSummary.totalTaxPST}}</el-link>
          </el-col>
          <el-col :span="3" class="table-cell">${{shopSummary.totalShopRechargePrice}}</el-col>
          <el-col :span="3" class="table-cell">${{shopSummary.totalCashRechargePrice}}</el-col>
          <el-col :span="3" class="table-cell">${{shopSummary.totalIncome}}</el-col>
          <el-col :span="3" class="table-cell">${{shopSummary.totalExpenses}}</el-col>
          <el-col :span="3" class="table-cell">${{shopSummary.totalAdminOrderExpenses}}</el-col>
          <el-col :span="3" class="table-cell">${{shopSummary.totalImportPrice}}</el-col>
      </el-row>
  </div>
    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" :element-loading-text="$t('Searching')" border fit
      highlight-current-row>
      <el-table-column align="center" :label="$t('序号')" type="index" :index="getIndex" width="50"></el-table-column>
      <el-table-column align="center" :label="$t('门店')" prop="shopName" />
      <el-table-column align="center" :label="$t('订单总金额')" prop="income">
          <template slot-scope="scope">
              {{ scope.row.orderActualPrice   | floorTwoDecimal}}
          </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('门店现金总充值')" prop="income">
          <template slot-scope="scope">
              {{ scope.row.cashRechargePrice   | floorTwoDecimal}}
          </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('额外总收入')" prop="income">
        <template slot-scope="scope">
          {{ scope.row.income   | floorTwoDecimal}}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('额外总支出')" prop="expend">
        <template slot-scope="scope">
          {{ scope.row.expenses | floorTwoDecimal }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('采购总支出')">
        <template slot-scope="scope">
          {{scope.row.adminOrderExpenses | floorTwoDecimal}}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('导入原料总支出')">
        <template slot-scope="scope">
          {{scope.row.importPrice | floorTwoDecimal}}
        </template>
      </el-table-column>
      <el-table-column width="220"  align="center" :label="$t('税费')">
        <template slot-scope="scope">
            <el-link type="primary">GST ${{scope.row.taxGST}}</el-link><el-divider direction="vertical"></el-divider>
            <el-link type="success">HST ${{scope.row.taxHST}}</el-link><el-divider direction="vertical"></el-divider>
            <el-link type="warning">PST ${{scope.row.taxPST}}</el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('Operate')" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['GET /admin/p/store_accountbook_detail']" type="primary" plain1 size="small"
            icon="el-icon-view" @click="handleDetail(scope.row)">{{$t('Details')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />

    <!-- 创建、编辑税费对话框 -->
    <el-dialog :visible.sync="dialogVisible" :title="dialogTitle">
      <el-form ref="bookAccountForm" :model="bookAccountForm" :rules="rules" status-icon label-position="left"
        label-width="120px" style="width: 400px; margin-left:50px;">
        <el-form-item :label="$t('入账时间')" prop="recordDate">
          <el-date-picker v-model="bookAccountForm.recordDate" type="date" value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="datePickerOptions"></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('类型')" prop="recordType">
          <el-select v-model="bookAccountForm.recordType">
            <el-option v-for="item in recordTypes" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('金额')" prop="amount">
          <el-input-number v-model="bookAccountForm.amount" :min="0" :controls="false" :precision="2"></el-input-number>
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="remark">
          <el-input type="textarea" v-model="bookAccountForm.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{$t('Cancel')}}</el-button>
        <el-button type="primary" @click="submit">{{$t('Confirm')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {shopListSummary,shopList, bookAccountListMonthGroup, bookAccountList, bookAccountLCreate } from '@/api/accountbook'
  import { allForPerm } from '@/api/shop'
  import BackToTop from '@/components/BackToTop'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  import store from '@/store'
  import { listCountryRegion, listSubRegion } from '@/api/region'

  export default {
    name: "bookAccountList",
    components: {
      BackToTop, Pagination
    },
    data() {
      return {
        // 当前店铺
        shop: store.state.user.shop,
        listLoading: true,
        total: 0,
        regionIds:undefined,
        listQuery: {
          page: 1,
          limit: 10,
          sort: 'add_time',
          order: 'desc',
          shopId:undefined,
          regionId:undefined
        },
        shopSummary:{},// 概况
        list: [],
        shops: [],
        countrys: [],
        dialogTitle: this.$t('添加'),
        dialogVisible: false,
        props: {
        value:'id',
        label: 'nameEn',
        children: 'children',
        checkStrictly: true
      },
        recordTypes: [{
          label: this.$t('收入'),
          value: 0
        }, {
          label: this.$t('支出'),
          value: 1
        }],
        bookAccountForm: {},
        rules: {
          recordDate: [
            { required: true, message: this.$t('入账时间不能为空'), trigger: 'blur' }
          ],
          recordType: [
            { required: true, message: this.$t('入账类型不能为空'), trigger: 'blur' }
          ],
          amount: [
            { required: true, message: this.$t('入账金额不能为空'), trigger: 'blur' }
          ],
          remark: [
            { required: true, message: this.$t('备注不能为空'), trigger: 'blur' }
          ]

        },
        datePickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now() - 8.64e6
          }
        }
      }
    },
    created() {
      this.getList()
      this.getCountrys()
      allForPerm().then(response => {
        this.shops = response.data.data.list
      })
    },
    methods: {
      getList() {
        if(this.regionIds&&this.regionIds.length>0){
          this.listQuery.regionId = this.regionIds[this.regionIds.length-1];
        }else{
          this.listQuery.regionId = undefined;
        }
        shopListSummary(this.listQuery)
          .then(response => {
            this.shopSummary = response.data.data
          })
          .catch(() => {
            this.shopSummary = []
          })
          shopList(this.listQuery)
          .then(response => {
            this.list = response.data.data.list
            this.total = response.data.data.total
            this.listLoading = false
          })
          .catch(() => {
            this.list = []
            this.total = 0
            this.listLoading = false
          })


      },
      getMonth(row) {
        return row.year + '-' + row.month
      },
      getProfit(row) {
        return row.income - row.expend
      },
      handleFilter() {
        this.getList()
      },
      handleDetail(row) {
        let query = {
          shopId: row.shopId,
          year: row.year,
          month: row.month
        };
        this.$router.push({ path: '/shop/account_book/detail', query: query })
      },
      submit() {
        this.$refs['bookAccountForm'].validate((valid) => {
          if (valid) {
            /*bookAccountLCreate(this.bookAccountForm).then(response => {
              this.dialogVisible = false
              this.$notify.success({
                title: this.$t('Success!'),
                message: this.$t('Success!')
              })
              this.getList()
            }).catch(response => {
              this.$notify.error({
                title: this.$t('Failed'),
                message: this.$t(response.data.errmsg)
              })
            })*/
          }
        })
      },
      handleAdd() {
        this.dialogVisible = true
        this.resetForm()
      },
      resetForm() {
        this.bookAccountForm = {}
      },
      getIndex(index) {
        return (index + 1) + (this.listQuery.page - 1) * this.listQuery.limit;
      },
      handleItemChange(val) {
        let step = val.length
        let query = {
          id: val[val.length - 1],
          type: 1
        }
        listSubRegion(query).then(response => {
          let result = this.findObject(this.countrys, val)
          response.data.data.list.forEach(child => {
            if (step <= 1) {
              result.children.push(this._.defaults(child, { children: [] }))
            } else {
              result.children.push(child)
            }
          })
        })
      },
      getCountrys() {
        listCountryRegion().then(response => {
          this.countrys = response.data.data.list.map(function (country) {
            return _.defaults(country, { children: [] })
          })
        })
      },
      findObject(arr, ids){
      // let result = undefined
      for(let i=0;i<=arr.length-1;i++){
        let obj = arr[i]
        if(ids.length == 1 && obj.id == ids[0]){
          return obj;
        }else if(obj.id == ids[0]){
          ids.shift()
          return this.findObject(obj.children, ids)
        }
      }
    },
    }
  }
</script>

<style scoped>
    .table-layout {
        margin-top: 20px;
        margin-bottom: 20px;
        border-left: 1px solid #DCDFE6;
        border-top: 1px solid #DCDFE6;
    }

    .table-cell {
        height: 60px;
        line-height: 40px;
        border-right: 1px solid #DCDFE6;
        border-bottom: 1px solid #DCDFE6;
        padding: 10px;
        font-size: 14px;
        color: #606266;
        text-align: center;
        overflow: hidden;
    }

    .table-cell-title {
        border-right: 1px solid #DCDFE6;
        border-bottom: 1px solid #DCDFE6;
        padding: 10px;
        background: #F2F6FC;
        text-align: center;
        font-size: 14px;
        color: #303133;
    }
</style>
